<template>
  <div >
    <div style="border:1px solid black;height:700px;">
    <el-container>
      <el-header>
        <span class="left">交易数据</span>
        <div style="float:right;">
          <a class="el-button" size="mini" id="dc">导出数据</a>
          <el-button-group class="header_right">
            <el-button size="mini"  autofocus="autofocus">昨天</el-button>
            <el-button size="mini">最近7天</el-button>
            <el-button size="mini">最近30天</el-button>
          </el-button-group>
          <el-date-picker
            class="header_right"
            size="mini"
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="fetchData()"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </div>
      </el-header>
    <el-main>
        <div>
        <div style="float:left;">
        <table border="1px">
          <tr>
            <th>浏览人数</th>
            <th>下单人数</th>
            <th>订单数</th>
            <th>下单件数</th>
            <th>有效订单数</th>
            <th>下单金额</th>
          </tr>
          <tr>
            <td v-for="(sta,index) in statis1" :key="index">{{sta}}</td>
          </tr>
          <tr>
            <th>退款金额</th>
            <th>付款人数</th>
            <th>付款订单数</th>
            <th>付款件数</th>
            <th>付款金额</th>
            <th>客单价</th>
          </tr>
          <tr>
            <td v-for="(sta,index) in statis2" :key="index">{{sta}}</td>
          </tr>
        </table>
        </div>
        <div id="sta" style="width: 400px;height:250px;float:left;margin-top:-40px;margin-left:100px;"></div>
        </div>
        </el-main>
    <el-footer>
        <div align="center" id="footer" style="width: 100%;height: 400px;"></div>
    </el-footer>
    </el-container>
    </div>
    <div  style="border:1px solid black;height:500px;margin-top:25px;">
      <el-container>
      <el-header>
        <span class="left">新老客户交易构成</span>
        <div style="float:right;">
          <a class="el-button" size="mini" id ='dc2'>导出数据</a>
          <el-button-group class="header_right">
            <el-button size="mini" class="header_right">本月</el-button>
            <el-button size="mini" class="header_right">上月</el-button>
          </el-button-group>
          <!-- <el-date-picker
          class="header_right"
          v-model="value1"
          size="mini"
          type="date"
          placeholder="选择日期">
        </el-date-picker> -->
        </div>
      </el-header>
    <el-main>
        <div>
        <div id="oldAndNew" style="width: 750px;height:300px;"></div>
        <div style="width: 50%;float: right;margin-top:-175px;margin-right: 10%;">
        <el-table :data="thisCustomerList" style="border:1px solid black;">
        <el-table-column prop="type" label="" width="75"></el-table-column>
        <el-table-column prop="sum" label="付款金额"></el-table-column>
        <el-table-column width="100" label="较前一月">
          <template slot-scope="scope">
              <span v-if="ratio1[scope.$index] >= 0">↑</span>
              <span v-else>↓</span>{{ratio1[scope.$index]}}%
            </template>
        </el-table-column>
        <el-table-column prop="num" label="付款人数"></el-table-column>
        <el-table-column width="100" label="较前一月">
          <template  slot-scope="scope">
              <span v-if="ratio2[scope.$index] >= 0">↑</span>
              <span v-else>↓</span> {{ratio2[scope.$index]}}%
            </template>
        </el-table-column>
        </el-table>
        </div>
      </div>
        </el-main>
    </el-container>
    </div>
    <div  style="border:1px solid black;height:350px;margin-top:25px;">
      <el-container>
      <el-header>
        <span class="left">交易数据</span>
        <div style="float:right;">
          <a class="el-button" size="mini" id ='dc3'>导出数据</a>
          <el-button-group class="header_right">
            <el-button size="mini" class="header_right" @click="moneyData(1)">昨天</el-button>
            <el-button size="mini" class="header_right" @click="moneyData(2)">最近7天</el-button>
            <el-button size="mini" class="header_right" @click="moneyData(3)">最近30天</el-button>
          </el-button-group>
          <el-date-picker
            class="header_right"
            size="mini"
            v-model="moneyDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="moneyData(0)"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </div>
      </el-header>
    <el-main>
        <div id="money" style="width: 750px;height:300px;margin-left:20%;"></div>
    </el-main>
    </el-container>
    </div>
    <div  style="border:1px solid black;height:350px;margin-top:25px;">
      <el-container>
      <el-header>
        <span class="left">订单来源构成</span>
        <div style="float:right;">
          <a class="el-button" size="mini" id ='dc3'>导出数据</a>
          <el-button-group class="header_right">
            <el-button size="mini" class="header_right" @click="source (0)">本月</el-button>
            <el-button size="mini" class="header_right" @click="source (1)">上月</el-button>
          </el-button-group>
          <el-date-picker
          class="header_right"
          v-model="value3"
          size="mini"
          type="date"
          @change="source (2)"
          placeholder="选择日期">
        </el-date-picker>
        </div>
      </el-header>
    <el-main>
        <div id="source" style="width: 750px;height:300px;margin-left:20%;"></div>
      <!-- <el-table :data="sourceData" style="width: 100%">
        <el-table-column prop="name" label="" width="100"></el-table-column>
        <el-table-column prop="sum" label="付款金额" width="200"></el-table-column>
        <el-table-column width="180" label="较前一月">
          <template slot-scope="scope">{{scope.$index}}</template>
        </el-table-column>
        <el-table-column prop="num" label="付款人数"></el-table-column>
        <el-table-column width="180" label="较前一月">
          <template slot-scope="scope">{{scope.$index}}</template>
        </el-table-column>
      </el-table> -->
    </el-main>
    </el-container>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value3: '',
      dateRange: ["2020-08-06", "2020-08-06"], // 查询日期
      statis1: [], // table第一行数据
      statis2: [], // table第一行数据
      dataTotal: [], // 漏斗图数据
      pre_order: '', // 下单率
      payment: '', // 付款率
      deal: '', // 成交率
      dateList: [], // 最近一周时间
      value1: '',
      thisCustomerList: [], // 本月新老客户交易构成数据
      lastCustomerList: [], // 上月新老客户交易构成数据
      nameList: [], // 新老客户
      kyList: [], // 新老用户及值
      ratio1: [], // 较前一月金额
      ratio2: [], // 较前一月付款人数
      moneyDate: ["2020-08-06", "2020-08-06"], // 交易数据日期
      peopleNum: [], // 统计金额人数
      value2: '2020-08-06', // 统计订单来源时间
      sourceData: [], // 订单
      orderMoneyNum: [],
      orderUserNum: [],
      lyList: ['web', 'app', '微信公众号', '微信小程序']
    };
  },
  methods: {
    async source (x) {
      var str = this.getTmonth()
      var str2 = this.getLmonth()
      // console.log(str)
      // console.log(str2)
      var params;
      if (x === 0) {
          params = str
      } else if (x === 2) {
          params = [this.value3, this.value3]
      } else {
          params = str2
      }
      const { data: res } = await this.$http.post(
        `orders/statis/orderMoneyNum`, params
      )
         var i = 0
         this.orderMoneyNum = []
      res.data.forEach(element => {
        this.orderMoneyNum.push({ value: element, name: this.lyList[i] })
        i += 1
      });
      const { data: res2 } = await this.$http.post(
        `orders/statis/orderUserNum`, params
      )
         var j = 0
         this.orderUserNum = []
      res2.data.forEach(element => {
        this.orderUserNum.push({ value: element, name: this.lyList[j] })
        j += 1
      });

      var myChart = this.$echarts.init(document.getElementById("source"))
      var option = {
        title: {
          text: "订单分析",
          x: "left"
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          data: this.lyList
        },
        series: [
          {
            name: "付款金额",
            type: "pie",
            radius: "35%",
            center: ["15%", "55%"],
            data: this.orderMoneyNum,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }, {
            name: "付款人数",
            type: "pie",
            radius: "35%",
            center: ["65%", "55%"],
            data: this.orderUserNum,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      }
      myChart.setOption(option)
    },
    async moneyData(x) {
      var date1 = '';
      var date2 = '';
            if (x === 1) {
                date1 = this.dateList[6];
            } else if (x === 2) {
                date1 = this.dateList[0]
                date2 = this.dateList[6]
            } else if (x === 3) {
                var str = this.getTmonth()
                date1 = str[0]
                date2 = str[1]
            } else {
                date1 = this.moneyDate[0];
                  date2 = this.moneyDate[1];
        }
      const { data: res } = await this.$http.get(
        `orders/statis/peopleNum?date1=${date1}&date2=${date2}`
      )
      this.peopleNum = res.data
      var myChart4 = this.$echarts.init(document.getElementById("money"))
      var option4 = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            containLabel: true
        },
          xAxis: {
              type: 'category',
              data: ['0-100元', '101-1000元', '1001-5000元', '5001-10000元', '10000+'],
              axisTick: {
                  alignWithLabel: true
              }
          },
          yAxis: [{
                  type: 'value',
                  name: '人数 /单位:(位)',
                  min: 0,
                  max: 100,
                  interval: 20,
                  axisLabel: {
                      formatter: '{value}'
                  }
              }],
          series: [{
              name: '人数',
              data: this.peopleNum,
              type: 'bar',
              barWidth: '40%'
          }]
      };
      myChart4.setOption(option4)
    },
    getTime(value) {
        var now = new Date(value);
        // var year = now.getYear();
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var days = now.getDate();
        // var dayOfWeek = now.getDay();
        // var hour = now.getHours();
        // var minutes = now.getMinutes();
        // var seconds = now.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (days >= 0 && days <= 9) {
            days = "0" + days;
        }
        // if (hour >= 0 && hour <= 9) {
        //     hour = "0" + hour;
        // }
        // if (minutes >= 0 && minutes <= 9) {
        //     minutes = "0" + minutes;
        // }
        // if (seconds >= 0 && seconds <= 9) {
        //     seconds = "0" + seconds;
        // }
        var time1 = year + "-" + month + "-" + days // + "  " + hour + ":" + minutes + ":" + seconds;
        return time1;
    },
    getDate() {
        const arr = []
        for (let i = 0; i < 7; i++) {
        const time = new Date(new Date().setDate((new Date().getDate() + i) - 7));
        const year = time.getFullYear();
        const month = `0${time.getMonth() + 1}`.slice(-2);
        const strDate = `0${time.getDate()}`.slice(-2);
        arr.push(`${year}-${month}-${strDate}`)
      }
      this.dateList = arr
    },
    getDate2(a) {
        const time = new Date(new Date().setDate((new Date().getDate()) - a));
        const year = time.getFullYear();
        const month = `0${time.getMonth() + 1}`.slice(-2);
        const strDate = `0${time.getDate()}`.slice(-2);
        var dates = `${year}-${month}-${strDate}`
        return dates
    },
    getTmonth() {
      var now = new Date()
      var nowMonth = now.getMonth()
      var nowYear = now.getFullYear()
      var monthStartDate = new Date(nowYear, nowMonth, 1);
      var monthEndDate = new Date(nowYear, nowMonth + 1, 0)
      var timeStar = this.getTime(monthStartDate)
      var timeEnd = this.getTime(monthEndDate)
      // console.log(timeStar + "==>" + timeEnd)
      var str = [timeStar, timeEnd]
      return str
    },
    getLmonth () {
      var nowdays = new Date()
            var year = nowdays.getFullYear()
            var month = nowdays.getMonth()
            if (month === 0) {
                month = 12
                year = year - 1
            }
            if (month < 10) {
                month = '0' + month
            }
            var myDate = new Date(year, month, 0)
            var startDate = year + '-' + month + '-01' //  00:00:00
            var endDate = year + '-' + month + '-' + myDate.getDate() // + ' 23:59:00'
            // console.log(startDate)
            // console.log(endDate)
            var str = [startDate, endDate]
            return str
    },
    ratio() {
      // 本月新老用户金额，人数
      // 同比=（当期值-去年同期值）/去年同期值×100％ = （当期值/去年同期值-1）×100％
        var sum1 = this.thisCustomerList[0].sum
        var num1 = this.thisCustomerList[0].num
        var sum2 = this.thisCustomerList[1].sum
        var num2 = this.thisCustomerList[1].num
      // 上月新老用户金额，人数
        var sum3 = this.lastCustomerList[0].sum
        var num3 = this.lastCustomerList[0].num
        var sum4 = this.lastCustomerList[1].sum
        var num4 = this.lastCustomerList[1].num

        var ratio1 = "100"
        var ratio2 = "100"
        var ratio3 = "100"
        var ratio4 = "100"
        // 判断上月是否为零
      if (sum3 !== 0) {
          ratio1 = (sum1 - sum3) / sum3
          ratio1 = (ratio1 * 100)
      }
      if (sum4 !== 0) {
          ratio2 = (sum2 - sum4) / sum4
          ratio2 = (ratio2 * 100)
      }
      if (num3 !== 0) {
          ratio3 = (num1 - num3) / num3
          ratio3 = (ratio3 * 100)
      }
      if (num4 !== 0) {
          ratio4 = (num2 - num4) / num4
          ratio4 = (ratio4 * 100)
      }
      // 判断两月是否都为零
      if (sum3 === 0 && sum1 === 0) {
          ratio1 = "0"
      }
      if (sum4 === 0 && sum2 === 0) {
          ratio2 = "0"
      }
      if (num3 === 0 && num1 === 0) {
          ratio3 = "0"
      }
      if (num4 === 0 && num2 === 0) {
          ratio4 = "0"
      }
      this.ratio1.push(ratio1)
      this.ratio1.push(ratio2)
      this.ratio2.push(ratio3)
      this.ratio2.push(ratio4)
    },
    dc () {
      // 第一个表格导出数据
      var html1 =
        "<html><head><meta charset='utf-8' /></head><body>" +
        document.getElementsByTagName("table")[0].outerHTML +
        "</body></html>";
      var blob1 = new Blob([html1], { type: "application/vnd.ms-excel" })
      // 第二个表格导出数据
      var html2 =
        "<html><head><meta charset='utf-8' /></head><body>" +
        document.getElementsByTagName("table")[1].outerHTML +
        "</body></html>";
      var blob2 = new Blob([html2], { type: "application/vnd.ms-excel" })
      // 绑定按钮
      var a1 = document.getElementById("dc");
      var a2 = document.getElementById("dc2");
      a1.href = URL.createObjectURL(blob1);
      a1.download = "交易数据统计1.xls"
      a2.href = URL.createObjectURL(blob2);
      a2.download = "交易数据统计2.xls"
    },
    async fetchData() {
      var dates = new Date()
      this.source(0)
      const date1 = this.dateRange[0];
      const date2 = this.dateRange[1];
      const { data: res } = await this.$http.get(
        `orders/statis/getList?date1=${date1}&date2=${date2}`
      )
      const { data: transaction } = await this.$http.get(
        `orders/statis/transaction`
      )
      this.thisCustomerList = []
      this.lastCustomerList = []
      this.thisCustomerList = transaction.data[0];
      this.lastCustomerList = transaction.data[1];
      this.nameList = []
      this.nameList.push(this.thisCustomerList[0].type)
      this.nameList.push(this.thisCustomerList[1].type)
      this.kyList = []
      this.kyList.push({ value: this.thisCustomerList[0].sum, name: this.thisCustomerList[0].type })
      this.kyList.push({ value: this.thisCustomerList[1].sum, name: this.thisCustomerList[1].type })
      // 循环对象获取属性名及属性值
      // 获得对象属性长度
      // var len = Object.getOwnPropertyNames(res.data.rows[0]).length
      for (var i = 0; i < res.data.rows.length; i++) {
          var len = 0; // 循环判断是第几行table的数据
          var b1 = 0; // table第一行判断
          var b2 = 0; // table第二行判断
      for (var p in res.data.rows[i]) {
        if (typeof res.data.rows[i][p] === "function") {
          res.data.rows[i][p]();
        } else {
          //    var props = p + ":" + res.data.rows[0][p]
          var props = res.data.rows[i][p];
          var sum = 0;
          if (props === null) {
            props = 0;
          }
          if (len < 8 && len > 1) {
              if (i === 0) {
                  sum = Number(props)
              } else {
                  sum = Number(props) + Number(this.statis1[b1])
              }
            this.statis1.splice(b1, 1, sum)
            b1 += 1
          } else if (len < 14 && len > 7) {
              if (i === 0) {
                  sum = Number(props)
              } else {
                  sum = Number(props) + Number(this.statis2[b2])
              }
            this.statis2.splice(b2, 1, sum)
            if (len === 13 && i > 0) {
               this.statis2.splice(5, 1, this.statis2[5] / 2)
            }
            b2 += 1
          }
          len += 1;
        }
      }
      }
        this.dataTotal = []
        this.dataTotal.push({ value: 20, name: '付款' })
        this.dataTotal.push({ value: 40, name: '下单' })
        this.dataTotal.push({ value: 60, name: '浏览' })
        this.payment = []
        this.pre_order = ((this.statis1[1] / this.statis1[0]) * 100).toFixed(2) + "%"
        this.payment = ((this.statis2[1] / this.statis1[1]) * 100).toFixed(2) + "%"
        this.deal = ((this.statis2[1] / this.statis1[0]) * 100).toFixed(2) + "%"
      var myChart = this.$echarts.init(document.getElementById("sta"))
      var myChart2 = this.$echarts.init(document.getElementById("footer"))
      var myChart3 = this.$echarts.init(document.getElementById("oldAndNew"))
      var option = {
        title: {
        },
         xAxis: {
                show: false
            },
            yAxis: {
                show: false,
                type: 'category',
                inverse: true,
                min: 0,
                max: 2
            },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c}%"
        },
        series: [
          {
                type: 'funnel',
                maxSize: '70%',
                left: '4%',
                gap: 2,
                label: {
                    position: 'inside',
                    rich: {
                        xx: {
                            padding: [6, 0]
                        }
                    }
                },
                data: this.dataTotal
            }, {
                type: 'pictorialBar',
                symbol: 'image://http://homework.mizholdings.com/kacha/kcsj/8351c72ed86c1a0c/.png',
                symbolSize: ['45%', 40],
                z: 1,
                symbolOffset: ['100%', 25],
                label: {
                    show: true,
                    position: 'right',
                    offset: [15, 25],
                    align: 'center',
                    backgroundColor: 'rgba(249,249,249,1)',
                    width: 100,
                    height: 40,
                    fontStyle: 'Microsoft YaHei',
                    formatter: function (d) {
                        var ins = '{s|转换率}\n' + `{x|${d.data.percent}}`;
                        return ins
                    },
                    rich: {
                        s: {
                            fontSize: 12,
                            color: '#545454',
                            padding: [5, 0, 12, 0]
                        },
                        x: {
                            fontSize: 14,
                            color: '#121212'
                        }
                    }
                },
                data: [{
                    value: 140,
                    percent: this.pre_order
                }, {
                    value: 140,
                    percent: this.payment
                }]
            }
        ]
      };
      var option2 = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['付款金额', '退款金额', '付款人数', '付款件数', '下单转换率', '付款转换率', '成交转换率']
        },
        xAxis: [{
            type: 'category',
            data: this.dateList,
            boundaryGap: false,
            axisLabel: {
            rotate: 30, // 旋转角度
            interval: 0
            }
        }],
        yAxis: [{
                type: 'value',
                name: '金额 /单位:￥',
                min: 0,
                max: 100000,
                interval: 12500,
                axisLabel: {
                    formatter: '{value}'
                }
            },
            {
                type: 'value',
                name: '转换率 /单位:%',
                min: 0,
                max: 100,
                interval: 25,
                axisLabel: {
                    formatter: '{value}'
                }
            }
        ],
        series: [{
                name: '付款金额',
                type: 'line',
                data: [4500, 0, 1500, 0, 0, 0, 0],
                yAxisIndex: 0
            },
            {
                name: '退款金额',
                type: 'line',
                data: [1500, 0, 1500, 0, 0, 0, 0],
                yAxisIndex: 0
            },
            {
                name: '付款人数',
                type: 'line',
                yAxisIndex: 0,
                data: [2, 0, 1, 0, 0, 0, 0]
            },
            {
                name: '下单转换率',
                type: 'line',
                yAxisIndex: 1,
                data: [4, 0, 2, 0, 0, 0, 0]
            },
            {
                name: '付款转换率',
                type: 'line',
                yAxisIndex: 1,
                data: [100, 0, 100, 0, 0, 0, 0]
            },
            {
                name: '成交转换率',
                type: 'line',
                yAxisIndex: 1,
                data: [50, 0, 100, 0, 0, 0, 0]
            }
        ]
    };
    var option3 = {
        title: {
          text: "金额分析",
          subtext: "目前只有本月和上月比较",
          x: "center"
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          orient: "vertical",
          left: "right",
          data: this.nameList
        },
        series: [
          {
            name: "金额",
            type: "pie",
            radius: "55%",
            center: ["35%", "60%"],
            data: this.kyList,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
    };
      myChart.setOption(option)
      myChart2.setOption(option2)
      myChart3.setOption(option3)
      this.dc()
      this.ratio()
      this.moneyData()
      var datee = new Date()
      console.log(this.dateMinus(dates, datee))
        if (this.dateMinus(dates, datee) > 1) {
          this.$message('网页加载较慢，感谢您的耐心等待!');
        }
    },
    dateMinus(data1, date2) {
            var s1 = data1.getTime()
            var s2 = date2.getTime()
            var total = (s2 - s1) / 1000
            var day = parseInt(total / (24 * 60 * 60))
            var afterDay = total - day * 24 * 60 * 60
            var hour = parseInt(afterDay / (60 * 60))
            var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60
            var min = parseInt(afterHour / 60)
            var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60
            return afterMin
        }
  },
  mounted() {
    this.getDate()
    this.fetchData();
  }
};
</script>

<style scoped>
body  {
    margin: 0;
    padding: 0;
}
.el-header {
  background-color: rgba(228, 228, 228, 1);
  color: #333;
  text-align: center;
  line-height: 60px;
}
.left {
  float: left;
}
.header_right {
  margin-left: 15px;
}
table {
  border-collapse: collapse;
  width: 125%;
  height: 150px;
}
table th {
  background-color: rgba(228, 228, 228, 1);
}
</style>
